package com.cjx.x5_webview

import android.app.Activity
import android.content.Intent
import android.graphics.PixelFormat
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.MenuItem
import android.view.View
import android.view.Window
import android.widget.FrameLayout
import com.tencent.smtt.export.external.interfaces.IX5WebChromeClient
import com.tencent.smtt.export.external.interfaces.WebResourceRequest
import com.tencent.smtt.sdk.ValueCallback
import com.tencent.smtt.sdk.WebChromeClient
import com.tencent.smtt.sdk.WebView
import com.tencent.smtt.sdk.WebViewClient
import io.flutter.plugin.common.MethodChannel
import kotlin.collections.HashMap

class X5WebViewActivity : Activity() {
    var chooserCallback: ValueCallback<Uri>? = null
    var webView: WebView? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestWindowFeature(Window.FEATURE_ACTION_BAR)
        window.setFormat(PixelFormat.TRANSLUCENT)
        webView = WebView(this)
        setContentView(webView)
        initView()
        initWebSetting()
    }

    private fun initView() {
        actionBar?.show()
        actionBar?.setDisplayHomeAsUpEnabled(true)
        title = intent.getStringExtra("title") ?: ""
        webView?.apply {
            layoutParams = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)
            val headers = intent.getSerializableExtra("headers") as HashMap<String,String>
            settings.javaScriptEnabled = true
            settings.domStorageEnabled = true
            loadUrl(intent.getStringExtra("url"), headers)
            val isUrlIntercept=intent.getBooleanExtra("isUrlIntercept",false)
            webViewClient = object : WebViewClient() {
                override fun shouldOverrideUrlLoading(view: WebView, url: String?): Boolean {
                    Log.e("X5WebViewActivity", "openurl:$url")
                    if(isUrlIntercept){
                        val map=HashMap<String,Any>()
                        map["url"] = url?:""
                        map["headers"] = HashMap<String,String>()
                        Log.e("X5WebViewActivity", "X5WebViewPlugin.methodChannel:${X5WebViewPlugin.methodChannel==null}")
                        X5WebViewPlugin.methodChannel?.invokeMethod("onUrlLoad",map)
                        return isUrlIntercept
                    }
                    view.loadUrl(url)

                    return super.shouldOverrideUrlLoading(view, url)
                }


                override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest?): Boolean {
                    Log.e("X5WebViewActivity", "openurl2:" + request?.url.toString())
                    if(isUrlIntercept){
                        val map=HashMap<String,Any>()
                        map["url"] = request?.url.toString()
                        map["headers"] = request?.requestHeaders?:HashMap<String,String>()
                        Log.e("X5WebViewActivity", "X5WebViewPlugin.methodChannel:${X5WebViewPlugin.methodChannel==null}")
                        X5WebViewPlugin.methodChannel?.invokeMethod("onUrlLoad",map)
                        return isUrlIntercept
                    }
                    view.loadUrl(request?.url.toString())
                    return super.shouldOverrideUrlLoading(view, request)
                }
                override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler?, error: SslError) {
                    val message =  when (error.primaryError) {
                        SslError.SSL_DATE_INVALID -> "证书日期无效"
                        SslError.SSL_EXPIRED -> "证书已过期。"
                        SslError.SSL_IDMISMATCH -> "主机名不匹配。"
                        SslError.SSL_INVALID -> "发生一般错误"
                        SslError.SSL_MAX_ERROR -> "不同SSL错误的数量。"
                        SslError.SSL_NOTYETVALID -> "证书尚未生效。"
                        SslError.SSL_UNTRUSTED -> "证书颁发机构不受信任。" // 自定义证书会执行到这个分支来
                        else -> "SSL证书错误,错误码：${error.primaryError}"
                    }
                    Timber.i("SSL错误：$message")

                    if (error.primaryError == SslError.SSL_UNTRUSTED) {
                        // 证书颁发机构不受信任，则我们需要判断一下是否是我们自己的自定义证书，是的话就忽略这个错误

                        val certificateFactory: CertificateFactory = CertificateFactory.getInstance("X.509")
                        val certificate = certificateFactory.generateCertificate(resources.openRawResource(R.raw.xxx)) as X509Certificate
                        val mX509CertificateFiled = SslCertificate::class.java.getDeclaredField("mX509Certificate").apply { isAccessible = true }
                        val mX509Certificate = mX509CertificateFiled.get(error.certificate) as X509Certificate
                        val certificates = HandshakeCertificates.Builder()
                            .addTrustedCertificate(certificate) // 信任指定的自定义证书
                            .addPlatformTrustedCertificates()  // 信任系统的预装证书，如果不信任系统证书的话，比如在访问https://m.baidu.com时将会出错
                            .build()

                        try {
                            certificates.trustManager.checkServerTrusted(arrayOf(mX509Certificate), "RSA")
                            Timber.i("是我们的自定义证书")
                            handler?.proceed()
                        } catch (e: java.lang.Exception) {
                            Timber.e(e, "非法证书")
                            handler?.cancel()
                        }
                    }
                    else {
                        super.onReceivedSslError(view, handler, error)
                    }
                }



            }
            webChromeClient = object : WebChromeClient() {

                override fun openFileChooser(p0: ValueCallback<Uri>?, p1: String?, p2: String?) {
                    chooserCallback=p0
                    Log.e("--cjx","p1:$p1 --- p2:$p2")
                    startActivityForResult(Intent(Intent.ACTION_PICK).apply {
                        type=p1
                    }
                        ,21212)

                }

            }
        }
    }

    /**
     * 设置WebSetting
     */
    private void initWebSetting() {
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSettings.setUserAgentString(webSettings.getUserAgentString() + " VersionCode/" + InstallUtil
            .getVersionCode(this));
        webSettings.setAppCacheMaxSize(1024 * 1024 * 8);
        webSettings.setAllowFileAccess(true);
        webSettings.setAppCacheEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        webSettings.setSupportZoom(true);
        webSettings.setGeolocationEnabled(true);
        webSettings.setDatabaseEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            android.R.id.home -> {
                finish()
            }
        }

        return super.onOptionsItemSelected(item)
    }


    override fun onDestroy() {
        super.onDestroy()
        webView?.destroy()
    }

    override fun onPause() {
        super.onPause()
        webView?.onPause()
    }

    override fun onResume() {
        super.onResume()
        webView?.onResume()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if(data!=null&&requestCode==21212&&chooserCallback!=null){
            chooserCallback?.onReceiveValue(data.data)
        }else{
            chooserCallback?.onReceiveValue(null)
        }
        chooserCallback=null

        super.onActivityResult(requestCode, resultCode, data)
    }
}